package com.jic.product.controller.after;

import com.alibaba.fastjson.JSONObject;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.manager.api.manage.SysDeptApi;
import com.jic.manager.request.SysDeptRequest;
import com.jic.manager.response.MemStoreResponse;
import com.jic.manager.response.SysDeptResponse;
import com.jic.order.api.OrderGoodsApi;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.request.GoodsPageQueryRequest;
import com.jic.product.after.request.MeStoreListRequest;
import com.jic.product.after.request.ProductSaleNumRequest;
import com.jic.product.after.request.SaveProductRequest;
import com.jic.product.after.response.*;
import com.jic.product.constant.consist.ResponseCode;
import com.jic.product.entity.Product;
import com.jic.product.entity.StoreInventory;
import com.jic.product.exception.AppRuntimeException;
import com.jic.product.manage.response.ProductResponse;
import com.jic.product.mapper.ProductMapper;
import com.jic.product.model.entity.ProductComment;
import com.jic.product.rest.response.ProductPropertyResponse;
import com.jic.product.rest.response.ProductPropertyResponseFront;
import com.jic.product.rest.response.ProductPropertyValueResponse;
import com.jic.product.rest.response.ProductResponseFront;
import com.jic.product.service.*;
import com.jic.product.store.request.MStoreFrozenRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by ZHU XIAN KUN on 2020/1/18
 * 跟据商品iD 查询  商品信息
 *
 * @Description:
 */
@Api(value = "商品中心-提供内部调用-feign", tags = "商品中心-提供内部调用-feign")
@RestController
@RequestMapping("/productList")
@Slf4j
public class ProductListController implements ProductListApi {

    @Resource
    OrderGoodsApi orderGoodsApi;
    @Autowired
    ProductService productService;

    @Autowired
    ProductSkuService productSkuService;

    @Resource
    SysDeptApi sysDeptApi;

    @Autowired
    StoreInventoryService storeInventoryService;

    @Autowired
    ProductCommentService productCommentService;
    @Resource
    MHotProductService mHotProductService;

    @Autowired
    private ProductMapper productMapper;

    @Override
    @ApiOperation(value = "查询商品库存", notes = "查询商品库存")
    public Boolean queryProductStock(String goodsId, Integer goodsNum) {
        StoreInventory storeInventory = new StoreInventory();
        storeInventory.setProductId(Long.valueOf(goodsId));
        List<StoreInventory> list = storeInventoryService.query(storeInventory);
        if (CollectionUtils.isNotEmpty(list)) {
            StoreInventory inventory = list.get(0);
            if (inventory.getAvailableStock() > goodsNum) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    @Override
    @ApiOperation(value = "查询商品详情", notes = "查询商品详情")
    public RestResult<List<ProductAfterResponse>> queryProductList(@RequestBody List<Long> productIds) {
        try {
            if (productIds == null) {
                return RestResult.error("9999", "参数不能为空");
            }
        } catch (Exception e) {
            log.error("error", e);
            return RestResult.error("9999", e.getLocalizedMessage());
        }
        return productService.queryProductListByProdId(productIds);

    }


    @Override
    @ApiOperation(value = "通过productId获取商家店铺信息", notes = "通过productId获取商家店铺信息")
    public RestResult<ShoppingCartResponse> getSkuByProdId(@RequestBody Long productId) {
        log.info("jic-product===============》通过productId获取商家店铺信息,{}", productId);
        ShoppingCartResponse shoppingCartResponse = new ShoppingCartResponse();
        if (productId != null) {
            shoppingCartResponse = productService.queryBusinessInfoByProductId(productId);
            Long deptId=shoppingCartResponse.getDeptId();
            //查询商品店铺logo
            if (deptId != null) {
                SysDeptRequest sysDeptRequest = new SysDeptRequest();
                sysDeptRequest.setId(deptId);
                RestResult<MemStoreResponse> storeInfo = sysDeptApi.getStoreInfoByDeptId(sysDeptRequest);
                if (null!=storeInfo && storeInfo.getData() != null) {
                    shoppingCartResponse.setStoreLogoUrl(storeInfo.getData().getStoreLogo());
                    shoppingCartResponse.setStoreName(storeInfo.getData().getStoreName());
                    shoppingCartResponse.setStoreId(storeInfo.getData().getId());
                    shoppingCartResponse.setDeptId(storeInfo.getData().getDeptPId());
                }
            }
        } else {
            return RestResult.error("9999", "参数不能为空");
        }

        return RestResult.success(shoppingCartResponse);
    }

    @ApiOperation(value = "查询商品信息", notes = "查询商品信息")
    @PostMapping("/queryProductInfoById")
    public RestResult<ProductAfterInfoByIdResponse> queryProductInfoById(@RequestBody Long productId) {
        log.info("jic-product===============》通过productId查询商品信息,{}", productId);
        ProductAfterInfoByIdResponse productAfterInfoByIdResponse = new ProductAfterInfoByIdResponse();
        try {
            if (productId != null) {
                productAfterInfoByIdResponse = productService.queryProductInfoById(productId);
                return RestResult.success(productAfterInfoByIdResponse);
            } else {
                return RestResult.error("9999", "参数不能为空");
            }

        } catch (Exception e) {
            log.error("error", e);
            return RestResult.error("9999", e.getLocalizedMessage());
        }


    }

    @ApiOperation(value = "根据商品三方编码查询商品信息", notes = "根据商品三方编码查询商品信息")
    @PostMapping("/queryProductInfoByThirdProductCode")
    public ProductAfterInfoByIdResponse queryProductInfoByThirdProductCode(String thirdProductCode) {
        log.info("jic-product===============》通过thirdProductCode查询商品信息,{}", thirdProductCode);
        ProductAfterInfoByIdResponse productAfterInfoByIdResponse = new ProductAfterInfoByIdResponse();
        try {
            if (thirdProductCode != null) {
                productAfterInfoByIdResponse = productService.queryProductInfoBythirdProductCode(thirdProductCode);
                return productAfterInfoByIdResponse;
            } else {
                return null;
            }

        } catch (Exception e) {
            log.error("error", e);
            return null;
        }
    }

    @ApiOperation(value = "保存平台给商家的商品", notes = "保存平台给商家的商品")
    @Override
    public RestResult<Boolean> saveMerchantProduct(@RequestBody SaveProductRequest productInfoRequest) {
        log.info("jic-product===============》保存平台给商家的商品,{}", productInfoRequest);
        return productService.saveMerchantProduct(productInfoRequest);
    }

    @ApiOperation(value = "保存商家给店铺的商品", notes = "保存商家给店铺的商品")
    @Override
    public RestResult<Boolean> saveStoreProduct(@RequestBody SaveProductRequest productInfoRequest) {
        log.info("jic-product===============》保存商家给店铺的商品,{}", productInfoRequest);
        return productService.saveStoreProduct(productInfoRequest);
    }

    @Override
    @ApiOperation(value = "查询店铺是否有商品", notes = "查询店铺是否有商品")
    public RestResult<List<MeStoreListResponse>> queryMeStoreList(@RequestBody List<MeStoreListRequest> meStoreListRequestList) {
        log.info("jic-product===============》查询店铺是否有商品,{}", meStoreListRequestList);
        return productService.queryMeStoreList(meStoreListRequestList);
    }

    @Override
    @ApiOperation(value = "根据商品ids查询商品", notes = "根据商品ids查询商品")
    public RestResult<List<ProductResponseFront>> queryProductListByIds(List<Long> productIds) {
        return productService.queryProductListByIds(productIds);
    }

    @Override
    @ApiOperation(value = "根据条件查询spu列表", notes = "根据条件查询spu列表")
    public RestResult<PageResult<GoodsPageQueryResponse>> queryByAllCondition(GoodsPageQueryRequest request) {
        return productService.queryByAllCondition(request);
    }

    @Override
    @ApiOperation(value = "营销-根据商品ID查询商品信息", notes = "根据条件查询spu列表")
    public RestResult<GoodsPageQueryResponse> queryMarketById(Long productId) {
        return productService.queryMarketById(productId);
    }

    @Override
    @ApiOperation(value = "订单-根据商品父ID查询商品信息", notes = "根据商品父ID查询商品信息")
    public RestResult<List<ProductAfterInfoByIdResponse>> queryProductInfoByParentId(Long productId) {
        return productService.queryProductInfoByParentId(productId);
    }

    @Override
    public RestResult<Boolean> frozenStock(MStoreFrozenRequest mStoreFrozenRequest) {
        return productService.frozenStock(mStoreFrozenRequest);
    }

    @Override
    @ApiOperation(value = "根据店铺id 查询全部商品 SPU和SKU")
    public List<ProductStoreInfo> queryProductByStoreId(GoodsPageQueryRequest goodsPageQueryRequest) {
        List<ProductStoreInfo> list = new ArrayList<>();
        if (null != goodsPageQueryRequest && CollectionUtils.isNotEmpty(goodsPageQueryRequest.getDeptIds())) {
            goodsPageQueryRequest.getDeptIds().forEach(item -> {
                //普通商品
//                Product product = new Product();
//                product.setStoreId(item);
//                product.setTypeOfProduct(1);
//                List<ProductStoreInfo> list1 = productService.queryProductByStoreIds(product);
//                list.addAll(list1);
                //系类子品 Spu
                Product product1 = new Product();
                product1.setStoreId(item);
                product1.setTypeOfProduct(2);
                List<ProductStoreInfo> list2 = productService.queryProductByStoreIds(product1);
                if (CollectionUtils.isNotEmpty(list2)) {
                    list2.forEach(productInfo->{
                        List<SysDeptResponse> deptList = sysDeptApi.query(new SysDeptRequest() {{
                            setId(productInfo.getDeptId());
                        }});
                        if (CollectionUtils.isNotEmpty(deptList)){
                            productInfo.setStoreId(deptList.get(0).getBusinessId());
                            productInfo.setStoreName(deptList.get(0).getDeptName());
                            List<SysDeptResponse> pDeptList = sysDeptApi.query(new SysDeptRequest() {{
                                setId(deptList.get(0).getPid());
                            }});
                            if(CollectionUtils.isNotEmpty(pDeptList)){
                                productInfo.setDeptId(pDeptList.get(0).getBusinessId());
                                productInfo.setDeptName(pDeptList.get(0).getDeptName());
                            }
                        }
                    });
                    list2.forEach(item1 -> {
                        Product product2 = new Product();
                        product2.setParentId(item1.getId());
                        List<ProductStoreInfo> list3 = productService.queryProductByStoreIds(product2);
                        list3.forEach(productInfo->{
                            List<SysDeptResponse> deptList = sysDeptApi.query(new SysDeptRequest() {{
                                setId(productInfo.getDeptId());
                            }});
                            if (CollectionUtils.isNotEmpty(deptList)){
                                productInfo.setStoreId(deptList.get(0).getBusinessId());
                                productInfo.setStoreName(deptList.get(0).getDeptName());
                                List<SysDeptResponse> pDeptList = sysDeptApi.query(new SysDeptRequest() {{
                                    setId(deptList.get(0).getPid());
                                }});
                                if(CollectionUtils.isNotEmpty(pDeptList)){
                                    productInfo.setDeptId(pDeptList.get(0).getBusinessId());
                                    productInfo.setDeptName(pDeptList.get(0).getDeptName());
                                }
                            }
                        });
                        item1.setChildren(list3);
                    });
                }
                list.addAll(list2);
            });
        }
        return list;
    }

    @Override
    public RestResult<PageResult<ProductStoreInfo>> queryProductPageByStoreId(GoodsPageQueryRequest goodsPageQueryRequest) {
        Page page = new Page();
        page.setLimit(goodsPageQueryRequest.getLimit());
        page.setStart(goodsPageQueryRequest.getStart());
        return RestResult.success(productService.queryProductPageByStoreIds(goodsPageQueryRequest, page));

    }

    @Override
    @ApiOperation(value = "根据spuId 查询skuList")
    public List<ProductStoreInfo> queryProductBySpuId(GoodsPageQueryRequest goodsPageQueryRequest) {
        if (CollectionUtils.isNotEmpty(goodsPageQueryRequest.getSpuIds())) {
            List<ProductStoreInfo> rest = new ArrayList<>();
            rest = productService.queryProductBySpuIds(goodsPageQueryRequest.getSpuIds(), goodsPageQueryRequest.getCanSale());
            return rest;
        } else {
            Product product = new Product();
            product.setParentId(goodsPageQueryRequest.getId());
            List<ProductStoreInfo> rest = productService.queryProductBySpuId(product);
            rest.forEach(item->{
                List<SysDeptResponse> deptList = sysDeptApi.query(new SysDeptRequest() {{
                    setId(item.getDeptId());
                }});
                if (CollectionUtils.isNotEmpty(deptList)){
                    item.setStoreId(deptList.get(0).getBusinessId());
                    item.setStoreName(deptList.get(0).getDeptName());
                    List<SysDeptResponse> pDeptList = sysDeptApi.query(new SysDeptRequest() {{
                        setId(deptList.get(0).getPid());
                    }});
                    if(CollectionUtils.isNotEmpty(pDeptList)){
                        item.setDeptId(pDeptList.get(0).getBusinessId());
                        item.setDeptName(pDeptList.get(0).getDeptName());
                    }
                }
            });
            return rest;
        }
    }

    @Override
    @ApiOperation(value = "根据条件查询spuList和skuList")
    public List<ProductStoreInfo> queryProductBySpuList(GoodsPageQueryRequest goodsPageQueryRequest) {
        return productService.queryProductBySpuList(goodsPageQueryRequest);
    }

    @Override
    @ApiOperation(value = "根据spu编码 模糊查询 返回spuId")
    public List<Long> queryProductByCode(GoodsPageQueryRequest goodsPageQueryRequest) {
        return productService.queryProductByCode(goodsPageQueryRequest);
    }

    @Override
    public List<ProductStoreInfo> queryProductListByThirdProductCodes(GoodsPageQueryRequest goodsPageQueryRequest) {
        return productService.queryProductListByThirdProductCodes(StringUtils.join(goodsPageQueryRequest.getThirdProductCodes(), ","));
    }

    /**
     * BBC接口 我的评论数统计
     * 根据用户id统计
     *
     * @return
     */
    @ApiOperation(value = "我的评论数统计")
    @ResponseBody
    @PostMapping("/queryMyCommentCount")
    @Override
    public RestResult<Long> queryMyCommentCount(Long memberId) {
        try {
            ProductComment productComment = new ProductComment();
            productComment.setMemberId(memberId);
            productComment.setType(1);
            //根据用户id只统计初次评论
            long myCommentCount = productCommentService.queryCount(productComment);
            return RestResult.success(myCommentCount);
        } catch (Exception e) {
            log.error("异常", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION);
        }
    }


    @Override
    @PostMapping("/updateProductSaleNum")
    @ApiOperation(value = "更新商品已售数量")
    public Boolean updateProductSaleNum(ProductSaleNumRequest productSaleNumRequest) {
       return productService.updateProductSaleNum(productSaleNumRequest);
    }

    @Override
    public  RestResult<List<ProductStoreInfo>> queryProductListBySpuId(Long spuId) {
        return RestResult.success(productService.queryProductListBySpuId(spuId));
    }

    @Override
    public List<HotProductResponse> queryProductListTopTen() {



        return mHotProductService.queryProductListTopTen();
    }

    @Override
    public RestResult<List<ProductPropertyResponse>> queryProductPropetyBySpuId(Long productId) {
        List<ProductPropertyResponseFront> productPropertyResponseFrontList = productMapper.queryPropertyNameById(productId);
        List<ProductPropertyResponse> productPropertyResponseList = new ArrayList<>();
        for (ProductPropertyResponseFront productPropertyResponseFront : productPropertyResponseFrontList) {
            ProductPropertyResponse productPropertyResponse = new ProductPropertyResponse();
            productPropertyResponse.setAttrId(productPropertyResponseFront.getAttNameId());
            productPropertyResponse.setAttrName(productPropertyResponseFront.getName());
            //根据商品属性名ids查询所有商品属性值数据
            List<ProductPropertyValueResponse> ppv = productMapper.queryPropertyValueById(productPropertyResponseFront.getId());
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(ppv)) {
                productPropertyResponse.setValueId(ppv.get(0).getValueId());
                productPropertyResponse.setValueName(ppv.get(0).getValueName());
                productPropertyResponseList.add(productPropertyResponse);
            }
        }
        return RestResult.success(productPropertyResponseList);
    }

    @Override
    public List<JSONObject> queryGoodsTypeById(String ids) {
        return productMapper.queryGoodsTypeById(ids);
    }
    @PostMapping("/queryBySupplierCode")
    @ApiOperation(value = "查询供应商对应的商品信息")
    @Override
    public List<ProductResponse> queryBySupplierCode(@RequestParam("supplierCode") String supplierCode) {
        return productService.queryBySupplierCode(supplierCode);
    }




}
